package com.ndood.core.social.qq.api;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 添加QQ实现类
 * wiki.connect.qq.com
 * 这边不能用@component，因为单例会造成安全问题 在QQServiceProvider中用new
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
	
	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
	
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
	
	private String appId;
	
	private String openId;
	
	private ObjectMapper objectMapper = new ObjectMapper();
	
	/**
	 * 构造方法 获取openId
	 */
	public QQImpl(String accessToken, String appId) {
		super(accessToken,TokenStrategy.ACCESS_TOKEN_PARAMETER);
		this.appId = appId;
		
		String url = String.format(URL_GET_OPENID, accessToken);
		String result = getRestTemplate().getForObject(url, String.class);
		System.out.println(result);
		this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
	}

	/**
	 * 获取用户信息
	 * https://graph.qq.com/user/get_user_info?oauth_consumer_key=101460438&openid=A0D90B71EEE52C812B0F1913C540D4B7
	 * 
	 * {
		    "ret": 0,
		    "msg": "",
		    "is_lost":0,
		    "nickname": "ndood \/kf",
		    "gender": "男",
		    "province": "马萨诸塞",
		    "city": "波士顿",
		    "year": "1899",
		    "constellation": "",
		    "figureurl": "http:\/\/qzapp.qlogo.cn\/qzapp\/101460438\/A0D90B71EEE52C812B0F1913C540D4B7\/30",
		    "figureurl_1": "http:\/\/qzapp.qlogo.cn\/qzapp\/101460438\/A0D90B71EEE52C812B0F1913C540D4B7\/50",
		    "figureurl_2": "http:\/\/qzapp.qlogo.cn\/qzapp\/101460438\/A0D90B71EEE52C812B0F1913C540D4B7\/100",
		    "figureurl_qq_1": "http:\/\/thirdqq.qlogo.cn\/qqapp\/101460438\/A0D90B71EEE52C812B0F1913C540D4B7\/40",
		    "figureurl_qq_2": "http:\/\/thirdqq.qlogo.cn\/qqapp\/101460438\/A0D90B71EEE52C812B0F1913C540D4B7\/100",
		    "is_yellow_vip": "0",
		    "vip": "0",
		    "yellow_vip_level": "0",
		    "level": "0",
		    "is_yellow_year_vip": "0"
		}

	 */
	@Override
	public QQUserInfo getUserInfo(){
		String url = String.format(URL_GET_USERINFO, appId, openId);
		String result = getRestTemplate().getForObject(url, String.class);
		// System.out.println(result);
		// 设置openId
		QQUserInfo userInfo = null;
		try {
			userInfo = objectMapper.readValue(result, QQUserInfo.class);
			userInfo.setOpenId(openId);
			return userInfo;
			
		} catch (Exception e) {
			throw new RuntimeException("获取用户信息失败", e);
		}
	}
}